﻿using AutoUpdate.Log;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;

namespace ScannerApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            var r = ScannerApp.Common.Authorize.CheckAuth();
            if (r.Item2 == -998&&r.Item2==-997)
            {
                MessageBox.Show(r.Item1, "提示");

                ScannerApp.Common.Authorize.Reflash(r.Item3);
                this.Shutdown();
                return;
            }
            if (r.Item2 == -999) {
                MessageBox.Show("缺少许可文件!无法运行!", "提示");

                ScannerApp.Common.Authorize.Reflash(r.Item3);
                this.Shutdown();
                return;
            }
            if (r.Item2 <= 0)
            {
                MessageBox.Show(" 您的系统许可证已到期，请与销售商或厂商联系！", "提示");

                ScannerApp.Common.Authorize.Reflash(r.Item3);
                this.Shutdown(); 
                return;
            }
            if (r.Item2 == 30)
            {
                UIAction(() =>
                {
                    MessageBox.Show(" 您的系统许可证还有30天到期，请与销售商或厂商联系!", "提示");

                    ScannerApp.Common.Authorize.Reflash(r.Item3);
                });
              
               
            }
            if (r.Item2 > 0 && r.Item2 < 7)
            {
                UIAction(() =>
                {
                    MessageBox.Show(" 您的系统许可证还有" + r.Item2 + "天到期，请与销售商或厂商联系!", "提示");

                    ScannerApp.Common.Authorize.Reflash(r.Item3);
                });
               
            }
            //首先注册开始和退出事件
            this.Startup += new StartupEventHandler(App_Startup);
            this.Exit += new ExitEventHandler(App_Exit);
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        void App_Startup(object sender, StartupEventArgs e)
        {
           
            //UI线程未捕获异常处理事件
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        void App_Exit(object sender, ExitEventArgs e)
        {
            //程序退出时需要处理的业务
        }
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                 Logger.Instance.WriteLog(publicclass.UserName + "App_DispatcherUnhandledException:" + e.Exception.Message, LogType.Error, "Error");

                MessageBox.Show("UI线程异常:" + e.Exception.Message);
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteLog(publicclass.UserName + "App_DispatcherUnhandledException:" + ex.Message, LogType.Error, "Error");

                //此时程序出现严重异常，将强制结束退出
                MessageBox.Show("UI线程发生致命错误！" + ex.Message);
            }
            finally
            {
                e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出      

            }


        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                StringBuilder sbEx = new StringBuilder();
                if (e.IsTerminating)
                {
                    sbEx.Append("非UI线程发生致命错误");
                }
                sbEx.Append("非UI线程异常：");
                if (e.ExceptionObject is Exception)
                {
                    sbEx.Append(((Exception)e.ExceptionObject).Message);
                }
                else
                {
                    sbEx.Append(e.ExceptionObject);
                }

                MessageBox.Show(sbEx.ToString());
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteLog(publicclass.UserName + "CurrentDomain_UnhandledException:" + ex.Message, LogType.Error, "Error");

            }
        }

        void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                //task线程内未处理捕获

                MessageBox.Show("Task线程异常：" + e.Exception.Message);
                e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
            }
            catch (Exception ex) {
                Logger.Instance.WriteLog(publicclass.UserName + "TaskScheduler_UnobservedTaskException:" + ex.Message, LogType.Error, "Error");

            }

        }

        private static System.Threading.Mutex mutex;
        //系统能够识别有名称的互斥，因此可以使用它禁止应用程序启动两次 
        //第二个参数可以设置为产品的名称:Application.ProductName 
        // 每次启动应用程序，都会验证名称为OnlyRun的互斥是否存在 
        protected override void OnStartup(StartupEventArgs e)
        {
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            //WPF 在电脑锁屏之后界面出现卡死现象
            RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
            mutex = new System.Threading.Mutex(true, "OnlyRun");
            if (mutex.WaitOne(0, false))
            {  //ThemeManager.Current.ChangeTheme(Application.Current, "Light.Green");
                
                base.OnStartup(e);
            }
            else
            {
                MessageBox.Show("主程序已经在运行！", "提示");
                this.Shutdown();
            }
        }
        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }



    }
}


